package com.huawei.security.handler;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huawei.common.BaseResult;
import com.huawei.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 自定义登录成功处理器
 */
@Component
public class AppLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        //处理乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //构建需要返回的JSON数据
        BaseResult result = new BaseResult();
        result.setMessage("恭喜您,登录成功");
        //生成token
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                (UsernamePasswordAuthenticationToken) authentication;
        User user = (User) usernamePasswordAuthenticationToken.getPrincipal();
        String token = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        //String token = JwtUtil.createToken(sysUser.getUserId(), sysUser.getUsername(), sysUser.getAuthorityList());
        result.setData(token);
        //往redis中存放token数据
        ValueOperations<String, String> vop = stringRedisTemplate.opsForValue();
        vop.set("token:" + token, JSON.toJSONString(user), 5, TimeUnit.MINUTES);
        //回写
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}
